<?php

namespace app\api\controller;

// use app\common\controller\Api;
// use EasyWeChat\Factory;
use think\Db;

use think\Config;
// use think\Validate;//验证
// use fast\Random;
// use fast\Http;

use app\api\controller\Tpmecms;
// use app\api\controller\Pay;



/**
 * 我的
 */
class Me extends Tpmecms
{

    protected $noNeedLogin = ['get_openid','get_user_mobile'];
    protected $noNeedRight = ['*'];

    protected $pros = null;



    // public $uid = '';
    public function _initialize()
    {
        parent::_initialize();
        
        // $this->car_fields = ['model','number','owner','end_time','regtime'];//,'driver_lic','car_type''use_type',

    }

    /**
     * 获取openid
     * @ApiSummary (里面有token，提交接口都要带上)
     * @param string $code
     * @return void
     */
    public function get_openid($code=null){
      
        $app = $this->get_app();
      
        $user = $app->auth->session($code);
        // halt($user);
        if(!empty($user['errcode'])){
            halt($user);
        }
        $openid = $user['openid'];
     
        $data = array();
        $data['openid'] = $openid;
        $user_data = Db::name('user')->where('openid',$openid)->find();
        if($user_data){
            $ret = $this->auth->direct($user_data['id']);
            $data = $this->auth->getUserinfo();
            // $data['uid'] = $user_data['id'];


            // $data['logintime'] = time();
            //开放平台
            if(empty($user_data['unionid']) && (!empty($user['unionid']))){
                Db::name('user')->where('openid',$openid)->update(['unionid'=>$user['unionid']]);
            }
        }else{

            $indata['openid'] = $openid;
            $indata['createtime'] = time();
            $indata['jointime'] = $indata['createtime'];
            $indata['joinip'] = $this->request->ip();
            $indata['logintime'] = time();
            $indata['status'] = 'normal';

            // $indata['stateswitch'] = 1;

            //开放平台
            if(!empty($user['unionid'])){
                $indata['unionid'] = $user['unionid'];
            }
            
     
            $id = Db::name('user')->insertGetId($indata);
            $ret = $this->auth->direct($id);

            $data = $this->auth->getUserinfo();
        }
        
        // $data['is']     = $data['uid'];//未知
        return json($data);
    }




    /**
     * 获取用户信息，没有授权的自动授权，类似登录
     * 
     * @return void
     */
    public function wx_get_user()
    {
        $app = $this->get_wx_gzh_app();
        $oauth = $app->oauth;

        // 未登录或没openid数据的
        if (empty(Session::get('wechat_user'))) {
            
            $url = $this->request->domain().'/index/index/code';//改成当前类的 访问路径，可以写成封装方法，怕一些用户看不懂
            $oauth->scopes(['snsapi_userinfo'])->redirect($url);//获取用户信息跳转
            //非Tp框架的可能要return

            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            $oauth->redirect()->send();
        }
            
        $user = Session::get('wechat_user');

        $Xiaohe = new Xiaohe;
        // halt($user);
        $Xiaohe->update_user_data($user,Session::get('sharer'));
        $user_data = $Xiaohe->openid_get_user($user['openid']);
        
         
        $ret = $this->auth->direct($user_data['id']);
        $token = $this->auth->getUserinfo()['token'];
        // halt($token);
        Session::set('token',$token);

        return $user;
    }




    /**
     * 修改用户的昵称和头像等
     *
     * @param string $nickname 昵称
     * @param string $img 头像
     * @param int $sex 1=男,2=女
     * @param string $school_id 学校ID
     * @param string $character_ids 个性标签
     * @param string $chsi_code 学信网验证码
     * @param string $images 学生证或录取通知书照片
     * @param string $match_ids 匹配IDS
     * @param string $birthday 生日
     * @param string $subject_status 话题开关:1=关闭,2=开启
     * @param string $bio 格言或简介
     * @return void
     */ 
    public function che_user($nickname=null,$img=null,$sex=null,$school_id=null,$bio=null,$character_ids=null,$chsi_code='',$city=null,$images='',$ltd_post=null,$prove_images=null,$visiting_switch=null,$match_ids=null,$birthday=null,$subject_status=null)
    {   
        // * @param string $ltd_post 公司职位
        // * @param string $prove_images 证明图
        // * @param string $visiting_switch 名片空间
        $u['id'] = $this->auth->id;
        if($nickname)
        $data['nickname'] = $nickname;
        
        if($img)
            $data['avatar'] = $img;
        if($sex)
            $data['sex'] = $sex;
        if($bio)
            $data['bio'] = $bio;

        if($school_id)
            $data['school_id'] = $school_id;
        // if($character_ids)
            $data['character_ids'] = $character_ids;
        // if($chsi_code)
            $data['chsi_code'] = $chsi_code;
        // if($city)
        // $data['city'] = $city;
        // if($images)
            $data['images'] = $images;

        if($birthday)
            $data['birthday'] = $birthday;

        if($match_ids)
            $data['match_ids'] = $match_ids;
        // if($ltd_post)
        // $data['ltd_post'] = $ltd_post;
        // if($prove_images)
        // $data['prove_images'] = $prove_images;
        if($school_id)
        if($this->auth->verify_status!='2')
            $data['verify_status'] = '1';

        if($subject_status)
        {
            $data['subject_status'] = $subject_status;
        }
        


        $res = Db::name('user')->where($u)->update($data);
        if($res){
            $this->success('修改成功');
        }
        $this->success('未做任何修改');
    }

    /**
     * 获取每日话题
     *
     * @return void
     */
    public function get_subject()
    {
        if($this->auth->subject_status=='2'){
            $time = strtotime(date('Y-m-d ').Config::get('site.subject_time'));
            if($time<=time()){
                $subject = Db::name('subject')->where('date',date('Y-m-d'))->find();
                if($subject){
                    // halt(Config::get('site.subject_time'));
              
                        $this->success('ok',$subject);
                    
    
    
                }else{
                    $this->error('今日无话题');
                }
            }else{
                $this->error('时间未到');
            }


        
        }else{
            $this->error('你已关闭话题');
        }
    }



     /**
     * 获取我的表情图列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_me_exp_list($page=1,$limit=10)
    {
        $list = Db::name('expuser')->where('uid',$this->auth->id)->page($page,$limit)->select();
        $this->success('ok',$list);
    }


    /**
     * 添加我的表情图
     *
     * @param string $image 表情图
     * @return void
     */
    public function add_me_exp($image=null)
    {
        $where['image'] = $image;
        $where['uid'] =  $this->auth->id;
        $res = Db::name('expuser')->where($where)->find();
        if(!$res){
            $where['createtime'] = time();
            $where['id'] = Db::name('expuser')->where($where)->insertGetId($where);
            $res = $where;
        }
        


        $this->success('ok',$res);
    }



    // /**
    //  * 修改用户信息
    //  *
    //  * @param string $job 职位
    //  * @param string $number 编号
    //  * @param string $ltd_name 公司全称
    //  * @param string $name 姓名
    //  * @param string $tel 电话
    //  * @param string $rig_model 钻机型号
    //  * @param string $p_name 推荐人
    //  * @param string $addr 地址
    //  * @return void
    //  */ 
    // public function update_user_data($job = null ,$number = null ,$ltd_name = null ,$name=null,$tel=null,$rig_model=null,$p_name=null,$addr=null)
    // {   
    //     // $u['id'] = $this->auth->id;
    //     // if($job)
    //     // $data['job'] = $job;

    //     // if($number)
    //     // $data['number'] = $number;

    //     // if($tel)
    //     // $data['tel'] = $tel;

    //     // if($rig_model)
    //     // $data['rig_model'] = $rig_model;

    //     // if($ltd_name)
    //     // $data['ltd_name'] = $ltd_name;


    //     if($name)
    //     $data['name'] = $name;


    //     // if($ltd_name)
    //     // $data['ltd_name'] = $ltd_name;


    //     // if($p_name)
    //     // $data['p_name'] = $p_name;       

    //     // if($addr)
    //     // $data['addr'] = $addr;      


      
    //     $res = Db::name('user')->where($u)->update($data);
    //     if($res){
    //         $this->success('修改成功');
    //     }
    //     $this->success('修改失败');
    // }


    /**
     * 获取用户信息
     *
     * @return void
     */
    public function get_user()
    {
        $list['user'] = Db::name('user')->where('id',$this->auth->id)->find();
        $list['follow'] = Db::name('fans')->where('fans_uid',$this->auth->id)->count();
        // $list['fans'] = Db::name('fans')->where('uid',$this->auth->id)->count();
        $list['character'] = Db::name('character')->where('id','in',$list['user']['character_ids'])->field('id,name')->select();//个性
        $list['school'] = Db::name('school')->where('id',$list['user']['school_id'])->value('name');//学校名
        $list['match'] = Db::name('character')->where('id','in',$list['user']['match_ids'])->field('id,name')->select();//匹配个性


        $this->success('ok',$list);
    }






    


    /**
     * 小程序授权获取手机号
     * @param string $encryptedData encryptedData
     * @param string $iv iv
     * @param string $code code
     * @return void
     */    
    public function get_user_mobile($code=null)
    {   
        $app = $this->get_app();
        $data = $this->request->param();
        $user = $app->auth->session($code);
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];

        $session = $user['session_key'];//$app->sns->getSessionKey($code);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);

        //修改手机号
        Db::name('user')->where('openid',$user['openid'])->update(['mobile'=>$decryptedData['phoneNumber']]);
        
        // return $decryptedData['phoneNumber'];
        $this->success($decryptedData['phoneNumber'],$decryptedData);
        // halt($decryptedData);
        
    }




    // /**
    //  * 获取我的邀请人数
    //  * 
    //  * @param boolean $self 掉接口不需要传
    //  * @return void
    //  */
    // public function user_get_my_share_num($self=false)
    // {
        
    //     $num = Db::name('user')
    //                 ->where('pid',$this->auth->id)
    //                 ->count();
    //     if($self){
    //         return $num; 
    //     }
    //     $this->success('👌',$num);
        

    // }


    // /**
    //  * 修改上级（通用）
    //  * 
    //  * @param string $pid 用户id
    //  * @return void
    //  */
    // public function update_pid($pid)
    // {
        
    //     $user = Db::name('user')->find($this->auth->id);
    //     if($user){
    //         if(!empty($user['pid'])){
    //             $this->error('已经有上级'.$user['pid']);
    //         }
    //     }

        
    //     $res_up = Db::name('user')->where('id',$this->auth->id)->update(['pid'=>$pid]);
    //     if($res_up){
    //         $this->success('绑定成功');
    //     }
    // } 

    // /**
    //  * 获取我的邀请列表👈
    //  * 
    //  * @param integer $page 1
    //  * @param integer $limit 200
    //  * @return void
    //  */
    // public function get_share_list($page = 1,$limit = 200)
    // {

    //     $list = Db::name('user')
    //                 ->where('pid',$this->auth->id)
    //                 ->order('createtime desc')
    //                 ->field([ '*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%m:%s") as date'])
    //                 ->select();
    //     $this->success(sizeof($list), $list);
    // }


    // /**
    //  * 获取我的分享二维码
    //  * 
    //  * @return void
    //  */
    // public function get_my_share_qr()
    // {
    //     $qr = new \addons\qrcode\controller\Index;
    //     if(empty($this->auth->qr)){
    //         $qr_path = $qr->get_qr(json_encode(['uid'=>$this->auth->id]));
            
    //         Db::name('user')->where('id',$this->auth->id)->update(['qr'=>$qr_path]);
    //         $this->auth->qr = $qr_path;
    //     }
    //     $this->success('qr',$this->auth->qr);
    // }




    /**
     * 修改收藏商品
     *
     * @param int $pro_id 商品id
     * @return void
     */
    public function update_gz_pro($pro_id)
    {
       
        $this->verify_pro_id($pro_id);
        // $this->is_uid();
        $data['uid'] = $this->auth->id;
        $data['pro_id'] = $pro_id;
        $res = Db::name('pro_gz')
            ->where($data)
            ->find();  
        
        if($res){
            $del = Db::name('pro_gz')->where($data)->delete();
            if($del){
           
                $this->success('已取消收藏',0);
                // $Dec = Db::name('pro')->where('id',$pro_id)->setDec('gz_num');//收藏数减
            }
        }else{            
            $data['time'] = time();
            $add = Db::name('pro_gz')->insert($data);
            if($add){
           
                $this->success('已收藏',1);
                // $Inc = Db::name('pro')->where('id',$pro_id)->setInc('gz_num');//收藏数加
            }
        }
    
    } 



    /**
     * 修改商品评论点赞👈🏼
     *
     * @param int $comment_id 评论id
     * @return void
     */
    public function update_comment_zan($comment_id)
    {
       
        $this->verify_comment_id($comment_id);
        // $this->is_uid();
        $data['uid'] = $this->auth->id;
        $data['comment_id'] = $comment_id;
        $res = Db::name('comment_zan')
            ->where($data)
            ->find();  
        
        if($res){
            $del = Db::name('comment_zan')->where($data)->delete();
            if($del){
           
                $this->success('已取消点赞',0);
       
            }
        }else{            
            $data['time'] = time();
            $add = Db::name('comment_zan')->insert($data);
            if($add){
           
                $this->success('已点赞',1);
                
            }
        }
    
    } 

    /**
     * 获取给我信息点赞的列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_give_me_adv_likes_list($page=1,$limit=10)
    {
        $list = Db::name('likes')->where('adv_uid',$this->auth->id)->page($page,$limit)->order('time desc')->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val['adv'] = Db::name('adv')->where('id',$val['adv_id'])->field('title,status,image,images')->find();
                $val['date'] = $this->TimeStr($val['time']);
                $val['user'] = $this->GetUserData1($val['uid']);
            }
        }
        $this->success('已点赞',$list);
    }


    /**
     * 获取给我信息评论的列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_give_me_adv_comment_list($page=1,$limit=10)
    {
        $list = Db::name('adv_comment')->where('adv_uid',$this->auth->id)->page($page,$limit)->order('time desc')->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val['adv'] = Db::name('adv')->where('id',$val['adv_id'])->field('title,status,image,images')->find();
                $val['date'] = $this->TimeStr($val['time']);
                $val['user'] = $this->GetUserData1($val['uid']);
            }
        }
        $this->success('已评论',$list);
    }

    /**
     * 获取我收藏的产品列表
     *
     * @param integer $page 1
     * @param integer $limit 9999
     * @return void
     */
    public function get_my_gz_pro_list($page=1,$limit=9999)
    {
        $pro_ids = Db::name('pro_gz')
            ->where('uid',$this->auth->id)
            ->page($page,$limit)
            ->column('pro_id');
        $pro_list = Db::name('pro')->where('id','in',$pro_ids)->select();
        foreach ($pro_list as $key => &$val) {
            $val['specs'] = $this->get_prospecs($val['id']);
        }
        $this->success('ok',$pro_list);
    }




}